﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;

namespace Marmat.Common.Http.Attributes
{
    /// <summary>
    /// 表示此请求的超时时间
    /// </summary>
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)]
    [DebuggerDisplay("Timeout = {TimeSpan}")]
    public class TimeoutAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 指定请求的超时时间
        /// </summary>
        /// <param name="milliseconds">超时时间的毫秒数</param>
        public TimeoutAttribute(int milliseconds)
        {
            this.TimeSpan = System.TimeSpan.FromMilliseconds(milliseconds);
        }

        /// <summary>
        /// 指定请求的超时时间
        /// </summary>
        /// <param name="milliseconds">超时时间的毫秒数</param>
        public TimeoutAttribute(double milliseconds)
        {
            this.TimeSpan = System.TimeSpan.FromMilliseconds(milliseconds);
        }
        /// <summary>
        /// 获取超时时间
        /// </summary>
        public TimeSpan? TimeSpan { get; }

        /// <summary>
        /// 操作执行前做的事情
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ApiActionContext context)
        {
            context.Request.Timeout = (int)this.TimeSpan.Value.TotalMilliseconds;
        }
    }
}
